import { defineStore } from 'pinia'
import { ref } from 'vue'
import { login, logout, getUserInfo } from '@/api'

export const useUserStore = defineStore('user', () => {
  // 状态
  const token = ref(localStorage.getItem('token') || '')
  const userInfo = ref({
    id: '',
    username: '',
    nickname: '',
    avatar: '',
    roles: []
  })

  // actions
  const login = async (data) => {
    try {
      const res = await login(data)
      token.value = res.data.token
      localStorage.setItem('token', res.data.token)
      return res
    } catch (error) {
      console.error('登录失败:', error)
      throw error
    }
  }

  const getInfo = async () => {
    try {
      const res = await getUserInfo()
      userInfo.value = res.data
      return res
    } catch (error) {
      console.error('获取用户信息失败:', error)
      throw error
    }
  }

  const logoutAction = async () => {
    try {
      await logout()
      resetState()
    } catch (error) {
      console.error('退出登录失败:', error)
      throw error
    }
  }

  // 重置状态
  const resetState = () => {
    token.value = ''
    userInfo.value = {
      id: '',
      username: '',
      nickname: '',
      avatar: '',
      roles: []
    }
    localStorage.removeItem('token')
  }

  return {
    token,
    userInfo,
    login,
    getInfo,
    logout: logoutAction,
    resetState
  }
}) 